package com.qiuyuliantu.common.mail;

import com.qiuyuliantu.common.core.domain.entity.SysUserMail;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 邮箱工具类
 *
 * @author 卷卷
 */
public class MailUtils
{

    /**
    * @Remark: * @Param 邮件发送
    * @Date: 2024/11/21
    * @Authbor: lmx
    */
    public static void sendMail(SysUserMail userMail, List<String> receiveMails, String tile, String content) throws Exception {
        String host = userMail.getHost();
        String port = userMail.getPort();
        String sendMail = userMail.getmail()+(userMail.getType().equals("qq")?"@qq.com":"@163.com");
        String sendMailPasswd = userMail.getPassword();
        Properties prop = new Properties();
        prop.setProperty("mail.host",host);//设置发送方邮箱服务器
        prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
        prop.setProperty("mail.smtp.auth","true");//需要验证用户名密码
        prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        prop.setProperty("mail.smtp.socketFactory.fallback", "false");
        prop.setProperty("mail.smtp.socketFactory.port",port);//服务器端口

        //收件人的邮箱地址 将发送的邮箱转字符串数组
        for (String receiveMail : receiveMails){
            Session session = Session.getDefaultInstance(prop);
            Transport ts = session.getTransport();
            ts.connect(host, sendMail, sendMailPasswd);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sendMail));
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(receiveMail));
            //邮件的标题
            message.setSubject(tile);
            message.setContent(content,"text/html;charset=UTF-8");
            ts.sendMessage(message,message.getAllRecipients());
            ts.close();
        }


    }


}
